package com.fishing.controller;

import QL.*;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fishing.entity.Admin;
import com.fishing.entity.OperLog;
import com.fishing.keyrun.KeyManager;
import com.fishing.listener.LoginUserMap;
import com.fishing.service.*;
import com.fishing.util.MD5;
import com.fishing.util.*;
import com.fishing.util.personal.QLClientServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.security.PrivateKey;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/***
 * 后台用户管理
 * @author lrz
 * */
@Controller
public class AdminController{
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private LoginqueryService loginqueryservice;
    @Autowired
    private OperLogService operlogService;
    @Autowired
    private T_Role_AdminService t_role_adminservice;
    
    //设置日期格式
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    
    //region 跳转生成二维码页面
    @RequestMapping("imageCode")
	public ModelAndView imageCode(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView("image");
		return mav;
	}
    //endregion
	
    //region 跳转登录界面
	@RequestMapping("login")
	public ModelAndView login(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView("login");
		return mav;
	}
	//endregion
	
	//region 获取公钥
	@ResponseBody
	@RequestMapping(value="publickey",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
    public Map<String, Object> publickey(HttpServletRequest request){
		String public_key = KeyManager.getPublic_key();
		return new ResultMap().success().data("public_key", public_key);
    }
	//endregion
	
	//region 管理员行为统计
	@RequestMapping("operate/Statistics")
	public ModelAndView Statistics(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView ("System/Statistics");
		return mav;
	}
	//endregion
	
	//region 登录检测
	@ResponseBody
    @RequestMapping(value = "loginDo")
	public Map<String,Object> loginDo(String loginId, String pwd, String valiCode, HttpServletRequest request) throws Exception{
    	Map<String,Object> resultMap = new HashMap<String, Object>();
    	String newpwd = pwd.toString().replaceAll(" ", "+");
    	if(StringUtils.isEmpty(loginId)){
    		resultMap.put("code", 1);
			resultMap.put("msg", "账号不能为空！");
			insertLog(false, "", request);
			return resultMap;
    	}
    	
    	if(StringUtils.isEmpty(pwd)){
    		resultMap.put("code", 2);
			resultMap.put("msg", "密码为空！");
			insertLog(false, "", request);
			return resultMap;
    	}
//    	if(StringUtils.isEmpty(valiCode)){
//    		resultMap.put("code", 3);
//			resultMap.put("msg", "验证码为空！");
//			insertLog(false, "", request);
//			return resultMap;
//    	}
//    	Object o = request.getSession().getAttribute("rand");
//    	if(null == o){
//    		resultMap.put("code", 4);
//			resultMap.put("msg", "验证码失效，请重新输入！");
//			insertLog(false, "", request);
//			return resultMap;
//    	}
    	
//    	String code = o.toString();
//    	if(!code.equals(valiCode)){
//    		resultMap.put("code", 5);
//			resultMap.put("msg", "验证码输入错误！");
//			insertLog(false, "", request);
//			return resultMap;
//    	}
    	
    	
    	Admin admin = null;
		try {
			admin = this.adminService.selectByLoginId(loginId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(null == admin){
			resultMap.put("code", 6);
			resultMap.put("msg", "账号或密码错误！");
			insertLog(false, "", request);
			return resultMap;
		}
		boolean flag = false;
		
		// 将Base64编码后的私钥转换成PrivateKey对象
        PrivateKey privateKey = RSAUtil.string2PrivateKey(KeyManager.getPrivate_key());
        // 加密后的内容Base64解码
        byte[] base642Byte = RSAUtil.base642Byte(newpwd);
        // 用私钥解密
        byte[] privateDecrypt = RSAUtil.privateDecrypt(base642Byte, privateKey);
        // 解密后的明文
        String password = new String(privateDecrypt);
		try {
			password = MD5.digestfull(loginId + password);
			password = MD5.digestfull(loginId + password);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(!(flag && password.equals(admin.getPwd()))){
			resultMap.put("code", 7);
			resultMap.put("msg", "用户名或密码输入错误！");
			insertLog(false, "", request);
			return resultMap;
		}
		
		//这里的Constants.loginKey是用来保存查询的admin
		request.getSession().setAttribute(Constants.loginKey, admin);  //key-value,可以使用session.getAttribute("key")来取值
		request.getSession().setAttribute("Admintruename", admin.getTruename());
		request.getSession().setAttribute("ZoneId", admin.getZoneid());
		request.getSession().setAttribute("IP", getRequestInfromation.getIpAddress(request));
		request.getSession().setAttribute("AdminId", admin.getId());
		//把sessionID保存到map中
		LoginUserMap.setLoginUsers("username",request.getSession().getId());
		
		try {
			insertLog(true, "", request);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		/*try {
			Date  date = new Date();
			SimpleDateFormat simpledate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			Loginquery loginquery = new Loginquery();
			//存入管理员名字
			loginquery.setAdminName(admin.getTruename());
			//存入IP
			loginquery.setLoginIP(getRequestInfromation.getIpAddress(request));
			//存入登陆时间
			loginquery.setLoginTime(simpledate.format(date));
			//存入session
			loginquery.setSessionID(request.getSession().getId());
			this.loginqueryservice.insert(loginquery);
			
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		try {
			request.getSession().setAttribute("menus", this.roleService.queryAuthMaps("p_0",admin.getId())); //p_0=1
			String authStr = this.roleService.queryAuthsByAdminId(admin.getId());
			authStr = !StringUtils.isEmpty(authStr)?(","+authStr+","):authStr;
			request.getSession().setAttribute("AUTHSTR", authStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		resultMap.put("code", 0);
		resultMap.put("msg", "登录成功！");
    	return resultMap;
	}
	//endregion
	
	//region 退出登录
	@ResponseBody
	@RequestMapping(value="delete/out_catch",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public String out_catch(HttpServletRequest request) {
		Enumeration em = request.getSession().getAttributeNames();
		while(em.hasMoreElements()) {
			request.getSession().removeAttribute(em.nextElement().toString());
		}
		return "success";
	}
	//endregion
	
	//region 跳转管理员改变密码页面
	@RequestMapping("admin/toChangePassword")
	public ModelAndView toChangePassword(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("admin/ChangePassword");
		return mav;
	}
	//endregion
	
	//region 跳转管理员改变密码页面
	@RequestMapping("admin/addAdministratorview")
	public ModelAndView addAdministratorview(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("admin/administratorview");
		return mav;
	}
	//endregion
	
	//region 管理员改变密码
	@ResponseBody
	@RequestMapping(value="admin/changePassword",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public String changePassword(HttpServletRequest request,String username,String password) {
		//传入数据库，并更新 
		Admin admin = null;
		try {
			//加密
			password = MD5.digestfull(username + password);
			password = MD5.digestfull(username + password);
			
			admin = this.adminService.selectByLoginId(username);
			admin.setPwd(password);
			this.adminService.updatePwd(admin);
			return "200";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "404";
	}
	//endregion
	
	//region 跳转更改渠道和版本号页面
	@RequestMapping("admin/toGetChannel")
	public ModelAndView toAddChannel(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("admin/GetChannel");
		return mav;
	}
	//endregion
	
	//region 获取渠道和版本号
	@ResponseBody
	@RequestMapping(value="admin/getChannel",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public Map getChannel(HttpServletRequest request) {
		List<Map> list = new ArrayList<>();
		ButlerVersionUpdateConfigGetRequest req = new ButlerVersionUpdateConfigGetRequest();
		req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
		ButlerVersionUpdateConfigGetResponse rsp = new ButlerVersionUpdateConfigGetResponse();
		QLClientServer.server(req.ZoneId);
		QLClient.Execute(req,rsp);
		try {
			String[] strs = rsp.ConfigString.split("\\|");
			for(int i  = 0;i < strs.length;i++) {
				Map<String,Object> data = new HashMap<>();
				String[] strs2 = strs[i].split(",");
				for(int  j = 0;j < strs2.length;j++) {
					if(j == 0) data.put("Name", strs2[j]);
					if(j == 1) data.put("Version", strs2[j]);
				}
				list.add(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String,Object> map = new HashMap<>();
		int count;
		map.put("message", "");
		map.put("status", "200");
		map.put("count",count = list.size() > 0 ?list.size():0);
		map.put("data", list);
		return map;
	}
	//endregion
	
	//region 修改渠道和版本号
	@ResponseBody
	@RequestMapping(value="admin/modifyChannel",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public String  modifyChannel(HttpServletRequest request,String tableData) {
		ButlerVersionUpdateConfigSetRequest req = new ButlerVersionUpdateConfigSetRequest();
		ButlerVersionUpdateConfigSetResponse rsp = new ButlerVersionUpdateConfigSetResponse();
		String  strs = "";
		if(tableData != "" || tableData != null) {
			JSONArray array = new JSONArray().parseArray(tableData);
			for(int i = 0;i < array.size();i++) {
				JSONObject jsonobject = (JSONObject)array.get(i);
				strs += jsonobject.get("Name") + ",";
				strs += jsonobject.get("Version");
				//这里-1是因为,在最后一次 循环的时候不加|
				strs = i < array.size()-1?strs + "|":strs;
			}
			req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
			req.ConfigString = strs;
			QLClientServer.server(req.ZoneId);
			QLClient.Execute(req,rsp);
			return rsp.ErrMsg;
		}else {
			req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
			QLClientServer.server(req.ZoneId);
			QLClient.Execute(req,rsp);
			return rsp.ErrMsg;
		}
	}
	//endregion
	
	//region 跳转到增加渠道页面
	@RequestMapping("admin/AddChannel")
	public ModelAndView AddChannel(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("admin/AddChannel");
		return mav;
	}
	//endregion
	
	//region 跳转到管理员增加名单页面
	@RequestMapping("admin/toList")
	public ModelAndView toList(HttpServletRequest request)throws Exception{
		ModelAndView mav = new ModelAndView("admin/list");
		return mav;
	}
	//endregion
	
	//region 改变开关服时间
	@ResponseBody
	@RequestMapping(value="admin/GetZoneState",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public Map GetZoneState(HttpServletRequest request) {
		ButlerServiceOpenStateGetRequest req = new ButlerServiceOpenStateGetRequest();
		req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
		ButlerServiceOpenStateGetResponse rsp = new ButlerServiceOpenStateGetResponse();
		QLClientServer.server(req.ZoneId);
		QLClient.Execute(req,rsp);
		Map<String,Object> map = new HashMap<>();
		if(rsp.ErrMsg == null) {
			String stat = rsp.IsOpen == true?"开服":"关服";
			if(stat.equals("开服")) {
				map.put("state", stat);
				map.put("OpenTime", "\\");
			}else {
				map.put("state", stat);
				map.put("OpenTime", "开服时间为" +  rsp.OpenTime);
			}
			return map;
		}else {
			return null;
		}
	}
	//endregion
	
	//region 跳转到开关服务器页面
	@RequestMapping("admin/toGetZoneState")
	public ModelAndView toGetZoneState(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("admin/GetZoneState");
		return mav;
	}
	//endregion
	
	//region 开关服务器
	@ResponseBody
	@RequestMapping(value="admin/getChangeState",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public Map getChangeState(HttpServletRequest request) {
		ButlerServiceOpenStateGetRequest req = new ButlerServiceOpenStateGetRequest();
		req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
		ButlerServiceOpenStateGetResponse rsp = new ButlerServiceOpenStateGetResponse();
		QLClientServer.server(req.ZoneId);
		QLClient.Execute(req,rsp);
		Map<String,Object> map = new HashMap<>();
		//用于比较字符串转化为日期格式
		Date date = new Date();
		SimpleDateFormat simpledate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(rsp.ErrMsg == null) {
			map.put("state", rsp.IsOpen);
			map.put("OpenTime", rsp.OpenTime);
			String stat = rsp.IsOpen == true?"开服":"关服";
			if(stat.equals("开服")) {
				map.put("state", stat);
				map.put("OpenTime", "\\");
			}else {
				if(stat.equals("关服") && rsp.OpenTime.equals("")) {
					map.put("state", stat);
					map.put("OpenTime", "未设置开服时间");
				}else {
					try {
						//设置的时间
						date = simpledate.parse(rsp.OpenTime);
						int compareTo = date.compareTo(DateTime.now());
						//获得当前时间，时间格式为 yyyy-MM-dd HH:mm:ss
						//System.out.println(DateTime.now());
						stat = compareTo <= 0?"开服":"关服";
						if(stat.equals("开服")) {
							map.put("state", stat);
							map.put("OpenTime", "\\");
						}else {
							map.put("state", stat);
							map.put("OpenTime", "开服时间为" +  rsp.OpenTime);
						}
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
			}
			List list = new ArrayList<>();
			list.add(map);
			Map<String,Object> mapdata = new HashMap<>();
			mapdata.put("status", "200");
			mapdata.put("message", "");
			mapdata.put("data", JSONArray.toJSON(list));
			mapdata.put("count", 0);
			return mapdata;
		}else {
			return null;
		}
	}
	//endregion
	
	//region 跳转设置服务器状态
	@RequestMapping("admin/toSetZoneState")
	public ModelAndView toSetZoneState(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("admin/SetZoneState");
		return mav;
	}
	//endregion
	
	//region 设置服务器状态
	@ResponseBody
	@RequestMapping(value="admin/SetZoneState",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public String  SetZoneState(HttpServletRequest request,String OpenTime,Boolean state) {
		ButlerServiceOpenStateSetRequest req = new ButlerServiceOpenStateSetRequest();
		req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
		req.IsOpen = state;
		req.OpenTime = OpenTime;
		ButlerServiceOpenStateSetResponse rsp = new ButlerServiceOpenStateSetResponse();
		QLClientServer.server(req.ZoneId);
		QLClient.Execute(req,rsp);
		return rsp.ErrMsg;
	}
	//endregion
	
	//region 跳转特殊名单页面
	@RequestMapping("admin/tospecialcompetencieslist")
	public ModelAndView tospecialcompetencieslist(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("admin/specialcompetencieslist");
		return mav;
	}
	//endregion
	
	//region 设置特殊名单
	@ResponseBody
	@RequestMapping(value="admin/SpecialCompetenciesList",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public Map<String,Object>  specialcompetencieslist(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<>();
		ButlerBlockMixedGetAllRecordsRequest req = new ButlerBlockMixedGetAllRecordsRequest();
		req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
		ButlerBlockMixedGetAllRecordsResponse rsp = new ButlerBlockMixedGetAllRecordsResponse();
		QLClientServer.server(req.ZoneId);
		QLClient.Execute(req,rsp);
		if(rsp.ErrMsg == "" || rsp.ErrMsg == null) {
			map.put("status", "200");
			map.put("message", "");
			map.put("data", rsp.InfoList);
			map.put("count", rsp.InfoList.size());
			return map;
		}else {
			map.put("status", "200");
			map.put("message", "");
			map.put("data", 0);
			map.put("count", 0);
			return map;
		}
	}
	//endregion
	
	//region 移除特殊名单
	@ResponseBody
	@RequestMapping(value="admin/RemoveNameList",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public String  RemoveNameList(HttpServletRequest request,String RemoveId,String RemoveReason) {
		ButlerBlockMixedRemoveRequest req = new ButlerBlockMixedRemoveRequest();
		req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
		req.RemoveId = Integer.parseInt(RemoveId);
		req.RemoveReason = RemoveReason;
		req.RemoveOperator = (String) request.getSession().getAttribute("Admintruename");
		ButlerBlockMixedRemoveResponse rsp = new ButlerBlockMixedRemoveResponse();
		QLClientServer.server(req.ZoneId);
		QLClient.Execute(req,rsp);
		if(rsp.ErrMsg == "" || rsp.ErrMsg == null) {
			return "success";
		}else {
			return "fail";
		}
	}
	//endregion
	
	//region 跳转移除名单页面
	@RequestMapping("admin/toremovenamelist")
	public ModelAndView toremovenamelist(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("admin/removenamelist");
		return mav;
	}
	//endregion
	
	//region 跳转增加名单页面
	@RequestMapping("admin/toaddnamelist")
	public ModelAndView toaddnamelist(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("admin/addnamelist");
		return mav;
	}
	//endregion
	
	//region 增加名单
	@ResponseBody
	@RequestMapping(value="admin/AddNameList",method = RequestMethod.POST,produces="text/html;charset=UTF-8")
	public String  AddNameList(HttpServletRequest request,String BlockType,String BlockValue,String BlockReason) {
		ButlerBlockMixedAddRequest req = new ButlerBlockMixedAddRequest();
		req.ZoneId = (Integer)request.getSession().getAttribute("ZoneId");
		req.BlockType = Integer.parseInt(BlockType);
		req.BlockValue = BlockValue;
		req.BlockReason = BlockReason;
		req.BlockOperator = (String)request.getSession().getAttribute("Admintruename");
		ButlerBlockMixedAddResponse rsp = new ButlerBlockMixedAddResponse();
		QLClientServer.server(req.ZoneId);
		QLClient.Execute(req,rsp);
		if(rsp.ErrMsg == "" || rsp.ErrMsg == null) {
			return "success";
		}else {
			return "fail";
		}
	}
	//endregion

	//region 插入日志
	public void insertLog(boolean flag, String msg, HttpServletRequest request) throws Exception{
		//插入日志
		OperLog ol = new OperLog();
		int type = 1;
		ol.setType(type);
		ol.setAdminname((String)request.getSession().getAttribute("Admintruename"));
		ol.setServiceName("登陆系统"+(StringUtils.isEmpty(msg)?"":",提示:"+msg));
		ol.setAdminId(1);
		ol.setEventexplain(null);
		ol.setCreateTime((new java.util.Date()));
		ol.setUserid(null);
		ol.setOperResult(flag == true ? "成功" : "失败");
		ol.setIp((String)request.getSession().getAttribute("IP"));
		this.operlogService.insert(ol);
		//System.out.println(this.operlogService.insert(ol));
	}
	//endregion
}









